<template>
  <div class="analytics-dashboard">
    <el-card class="page-header">
      <template #header>
        <div class="header-title">
          <h2>数据总览</h2>
          <div class="filter-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              @change="handleDateChange"
            />
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
          </div>
        </div>
      </template>
    </el-card>

    <!-- 数据概览卡片 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <template #header>
              <div class="stats-header">
                <span>用户总数</span>
                <el-tooltip content="平台注册的总用户数量" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="stats-content">
              <div class="stats-value">{{ stats.totalUsers }}</div>
              <div class="stats-chart">
                <div ref="userTrendChart" class="mini-chart"></div>
              </div>
              <div class="stats-footer">
                <span>较上月</span>
                <span class="trend-value" :class="stats.usersTrend > 0 ? 'up' : 'down'">
                  {{ stats.usersTrend > 0 ? '+' : '' }}{{ stats.usersTrend }}%
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <template #header>
              <div class="stats-header">
                <span>内容总数</span>
                <el-tooltip content="平台发布的所有内容数量" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="stats-content">
              <div class="stats-value">{{ stats.totalContents }}</div>
              <div class="stats-chart">
                <div ref="contentTrendChart" class="mini-chart"></div>
              </div>
              <div class="stats-footer">
                <span>较上月</span>
                <span class="trend-value" :class="stats.contentsTrend > 0 ? 'up' : 'down'">
                  {{ stats.contentsTrend > 0 ? '+' : '' }}{{ stats.contentsTrend }}%
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <template #header>
              <div class="stats-header">
                <span>销售总额</span>
                <el-tooltip content="平台商品累计销售金额" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="stats-content">
              <div class="stats-value">¥{{ stats.totalSales }}</div>
              <div class="stats-chart">
                <div ref="salesTrendChart" class="mini-chart"></div>
              </div>
              <div class="stats-footer">
                <span>较上月</span>
                <span class="trend-value" :class="stats.salesTrend > 0 ? 'up' : 'down'">
                  {{ stats.salesTrend > 0 ? '+' : '' }}{{ stats.salesTrend }}%
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stats-card" shadow="hover">
            <template #header>
              <div class="stats-header">
                <span>日活用户</span>
                <el-tooltip content="每日活跃用户数量" placement="top">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <div class="stats-content">
              <div class="stats-value">{{ stats.dailyActiveUsers }}</div>
              <div class="stats-chart">
                <div ref="dauTrendChart" class="mini-chart"></div>
              </div>
              <div class="stats-footer">
                <span>较上月</span>
                <span class="trend-value" :class="stats.dauTrend > 0 ? 'up' : 'down'">
                  {{ stats.dauTrend > 0 ? '+' : '' }}{{ stats.dauTrend }}%
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 主要图表 -->
    <div class="main-charts">
      <el-row :gutter="20">
        <el-col :xs="24" :lg="16">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>平台数据趋势</span>
                <el-radio-group v-model="mainTrendType" size="small">
                  <el-radio-button label="user">用户</el-radio-button>
                  <el-radio-button label="content">内容</el-radio-button>
                  <el-radio-button label="order">订单</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="mainTrendChart" class="chart"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="8">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>流量来源分布</span>
              </div>
            </template>
            <div ref="trafficSourceChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>用户活跃时段分布</span>
              </div>
            </template>
            <div ref="userTimeChart" class="chart"></div>
          </el-card>
        </el-col>
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>用户留存率</span>
              </div>
            </template>
            <div ref="retentionChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 其他数据 -->
    <div class="data-tables">
      <el-row :gutter="20">
        <el-col :xs="24" :md="12">
          <el-card class="table-card">
            <template #header>
              <div class="table-header">
                <span>热门搜索关键词</span>
              </div>
            </template>
            <el-table :data="hotKeywords" style="width: 100%" size="small">
              <el-table-column type="index" width="50" align="center" />
              <el-table-column prop="keyword" label="关键词" />
              <el-table-column prop="count" label="搜索次数" width="100" />
              <el-table-column prop="trend" label="趋势" width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.trend > 0 ? 'success' : 'danger'" size="small">
                    {{ scope.row.trend > 0 ? '上升' : '下降' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :xs="24" :md="12">
          <el-card class="table-card">
            <template #header>
              <div class="table-header">
                <span>热门页面访问</span>
              </div>
            </template>
            <el-table :data="hotPages" style="width: 100%" size="small">
              <el-table-column type="index" width="50" align="center" />
              <el-table-column prop="page" label="页面" show-overflow-tooltip />
              <el-table-column prop="views" label="浏览量" width="90" />
              <el-table-column prop="avgStay" label="平均停留时间" width="120" />
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
// import { initChart } from '@/utils/echarts'

// 图表DOM引用
const userTrendChart = ref(null)
const contentTrendChart = ref(null)
const salesTrendChart = ref(null)
const dauTrendChart = ref(null)
const mainTrendChart = ref(null)
const trafficSourceChart = ref(null)
const userTimeChart = ref(null)
const retentionChart = ref(null)

// 图表实例
const userTrendChartEl = ref(null)
const contentTrendChartEl = ref(null)
const salesTrendChartEl = ref(null)
const dauTrendChartEl = ref(null)
const mainTrendChartEl = ref(null)
const trafficSourceChartEl = ref(null)
const userTimeChartEl = ref(null)
const retentionChartEl = ref(null)

// 日期范围和趋势类型
const dateRange = ref([])
const mainTrendType = ref('user')

// 数据统计
const stats = reactive({
  totalUsers: 12586,
  usersTrend: 8.3,
  totalContents: 586,
  contentsTrend: 12.5,
  totalSales: '158,652.35',
  salesTrend: 15.8,
  dailyActiveUsers: 4213,
  dauTrend: 5.2
})

// 热门搜索关键词数据
const hotKeywords = ref([
  { keyword: '健康饮食', count: 2156, trend: 1 },
  { keyword: '瑜伽初学', count: 1852, trend: 1 },
  { keyword: '血压计', count: 1544, trend: 1 },
  { keyword: '减肥食谱', count: 1320, trend: -1 },
  { keyword: '颈椎病', count: 1289, trend: 1 },
  { keyword: '睡眠质量', count: 1145, trend: -1 },
  { keyword: '中医养生', count: 1023, trend: 1 },
  { keyword: '高血压', count: 987, trend: -1 }
])

// 热门页面数据
const hotPages = ref([
  { page: '首页', views: 18562, avgStay: '03:25' },
  { page: '健康知识/颈椎病的自我缓解方法', views: 5289, avgStay: '05:40' },
  { page: '健身指南/初学者健身计划', views: 4852, avgStay: '06:12' },
  { page: '商城/专业血压计', views: 3542, avgStay: '02:50' },
  { page: '健康知识/健康饮食指南', views: 3125, avgStay: '04:30' },
  { page: '商城/智能体脂秤', views: 2854, avgStay: '02:35' },
  { page: '健康工具/BMI计算器', views: 2546, avgStay: '01:42' },
  { page: '健康知识/改善睡眠质量的方法', views: 2358, avgStay: '04:55' }
])

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 初始化图表
const initCharts = () => {
  // 由于缺少echarts依赖，这里暂时不初始化图表
  // 实际代码应该类似以下：
  
  // 初始化迷你趋势图
  initMiniCharts()
  
  // 初始化主趋势图
  updateMainTrendChart()
  
  // 初始化流量来源饼图
  // initTrafficSourceChart()
  
  // 初始化用户活跃时段图
  // initUserTimeChart()
  
  // 初始化用户留存率图
  // initRetentionChart()
}

// 初始化迷你趋势图
const initMiniCharts = () => {
  // 用户趋势迷你图
  // const userOption = {
  //   grid: { top: 8, right: 8, bottom: 8, left: 8 },
  //   xAxis: { show: false, type: 'category' },
  //   yAxis: { show: false },
  //   series: [{
  //     type: 'line',
  //     data: [12, 15, 18, 14, 22, 20, 25],
  //     smooth: true,
  //     showSymbol: false,
  //     lineStyle: { width: 2, color: '#409EFF' },
  //     areaStyle: { 
  //       color: {
  //         type: 'linear',
  //         x: 0, y: 0, x2: 0, y2: 1,
  //         colorStops: [
  //           { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
  //           { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
  //         ]
  //       }
  //     }
  //   }]
  // }
  // userTrendChartEl.value = initChart(userTrendChart.value, userOption)
  
  // 内容趋势迷你图
  // const contentOption = {
  //   grid: { top: 8, right: 8, bottom: 8, left: 8 },
  //   xAxis: { show: false, type: 'category' },
  //   yAxis: { show: false },
  //   series: [{
  //     type: 'line',
  //     data: [5, 8, 6, 9, 12, 10, 14],
  //     smooth: true,
  //     showSymbol: false,
  //     lineStyle: { width: 2, color: '#67C23A' },
  //     areaStyle: { 
  //       color: {
  //         type: 'linear',
  //         x: 0, y: 0, x2: 0, y2: 1,
  //         colorStops: [
  //           { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
  //           { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
  //         ]
  //       }
  //     }
  //   }]
  // }
  // contentTrendChartEl.value = initChart(contentTrendChart.value, contentOption)
  
  // 销售额趋势迷你图
  // const salesOption = {
  //   grid: { top: 8, right: 8, bottom: 8, left: 8 },
  //   xAxis: { show: false, type: 'category' },
  //   yAxis: { show: false },
  //   series: [{
  //     type: 'line',
  //     data: [1500, 2200, 1800, 2400, 3000, 2600, 3500],
  //     smooth: true,
  //     showSymbol: false,
  //     lineStyle: { width: 2, color: '#E6A23C' },
  //     areaStyle: { 
  //       color: {
  //         type: 'linear',
  //         x: 0, y: 0, x2: 0, y2: 1,
  //         colorStops: [
  //           { offset: 0, color: 'rgba(230, 162, 60, 0.3)' },
  //           { offset: 1, color: 'rgba(230, 162, 60, 0.1)' }
  //         ]
  //       }
  //     }
  //   }]
  // }
  // salesTrendChartEl.value = initChart(salesTrendChart.value, salesOption)
  
  // 日活用户趋势迷你图
  // const dauOption = {
  //   grid: { top: 8, right: 8, bottom: 8, left: 8 },
  //   xAxis: { show: false, type: 'category' },
  //   yAxis: { show: false },
  //   series: [{
  //     type: 'line',
  //     data: [3800, 4200, 3900, 4500, 4300, 4800, 5100],
  //     smooth: true,
  //     showSymbol: false,
  //     lineStyle: { width: 2, color: '#F56C6C' },
  //     areaStyle: { 
  //       color: {
  //         type: 'linear',
  //         x: 0, y: 0, x2: 0, y2: 1,
  //         colorStops: [
  //           { offset: 0, color: 'rgba(245, 108, 108, 0.3)' },
  //           { offset: 1, color: 'rgba(245, 108, 108, 0.1)' }
  //         ]
  //       }
  //     }
  //   }]
  // }
  // dauTrendChartEl.value = initChart(dauTrendChart.value, dauOption)
}

// 更新主趋势图
const updateMainTrendChart = () => {
  // 由于缺少echarts依赖，暂时不实现
  // 实际代码可能如下所示：
  
  // const xData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
  // let yData = []
  // let title = ''
  
  // if (mainTrendType.value === 'user') {
  //   title = '用户增长趋势'
  //   yData = [
  //     { name: '新注册用户', type: 'bar', data: [580, 685, 720, 840, 920, 1050, 1180] },
  //     { name: '累计用户', type: 'line', 
  //       smooth: true,
  //       data: [9500, 10185, 10905, 11745, 12665, 13715, 14895],
  //       areaStyle: { opacity: 0.2 }
  //     }
  //   ]
  // } else if (mainTrendType.value === 'content') {
  //   title = '内容发布趋势'
  //   yData = [
  //     { name: '新增内容', type: 'bar', data: [45, 52, 68, 75, 82, 95, 106] },
  //     { name: '累计内容', type: 'line', 
  //       smooth: true,
  //       data: [320, 372, 440, 515, 597, 692, 798],
  //       areaStyle: { opacity: 0.2 }
  //     }
  //   ]
  // } else {
  //   title = '订单趋势'
  //   yData = [
  //     { name: '订单数', type: 'bar', data: [320, 285, 342, 365, 410, 445, 502] },
  //     { name: '销售额', type: 'line', 
  //       smooth: true,
  //       data: [28500, 26200, 32400, 34800, 38500, 42300, 47500],
  //       areaStyle: { opacity: 0.2 }
  //     }
  //   ]
  // }
  
  // if (!mainTrendChartEl.value) {
  //   mainTrendChartEl.value = initChart(mainTrendChart.value)
  // }
  
  // mainTrendChartEl.value.setOption({
  //   title: { text: title, left: 'center' },
  //   tooltip: { trigger: 'axis' },
  //   legend: { bottom: 0 },
  //   grid: { left: '3%', right: '4%', bottom: '60px', top: '60px', containLabel: true },
  //   xAxis: { type: 'category', data: xData },
  //   yAxis: { type: 'value' },
  //   series: yData
  // })
}

// 处理日期变化
const handleDateChange = () => {
  // 实际代码应该重新获取数据并更新所有图表
  ElMessage.success('日期范围已更新')
}

// 刷新数据
const refreshData = () => {
  ElMessage.success('数据已刷新')
  // 实际代码应该重新获取数据并更新所有图表
}

// 监听趋势类型变化
watch(mainTrendType, () => {
  updateMainTrendChart()
})

// 监听窗口大小变化
const resizeHandler = () => {
  // 调整所有图表大小
  userTrendChartEl.value?.resize()
  contentTrendChartEl.value?.resize()
  salesTrendChartEl.value?.resize()
  dauTrendChartEl.value?.resize()
  mainTrendChartEl.value?.resize()
  trafficSourceChartEl.value?.resize()
  userTimeChartEl.value?.resize()
  retentionChartEl.value?.resize()
}

// 生命周期钩子
onMounted(() => {
  // 设置默认日期范围为最近一个月
  dateRange.value = dateShortcuts[1].value()
  
  // 初始化所有图表
  initCharts()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', resizeHandler)
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', resizeHandler)
})
</script>

<style scoped>
.analytics-dashboard {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title h2 {
  margin: 0;
  font-size: 20px;
}

.filter-actions {
  display: flex;
  gap: 15px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stats-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.stats-header {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
}

.stats-content {
  padding: 5px 0;
}

.stats-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
  text-align: center;
}

.mini-chart {
  height: 50px;
  margin: 0 auto;
}

.stats-footer {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  color: #909399;
}

.trend-value {
  font-weight: 500;
}

.trend-value.up {
  color: #67c23a;
}

.trend-value.down {
  color: #f56c6c;
}

.main-charts {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 350px;
}

.data-tables {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  font-size: 15px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .header-title {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-actions {
    margin-top: 15px;
    flex-wrap: wrap;
  }
  
  .chart {
    height: 280px;
  }
}
</style> 